﻿using System;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Routing;
using UIShell.OSGi;

namespace Isaac.Joy.Mvc.Web
{
    public static class UrlExt
    {
        public static string BContent(this UrlHelper helper, string url)
        {
            string symbolicName = null;
            object area;
            if (helper.RequestContext.RouteData.DataTokens.TryGetValue("area", out area))
            {
                symbolicName = area as string;
            }
            else
            {
                var routeWithArea = helper.RequestContext.RouteData.Route as IRouteWithArea;
                if (routeWithArea != null)
                {
                    symbolicName = routeWithArea.Area;
                }
                var castRoute = helper.RequestContext.RouteData.Route as Route;
                if (castRoute != null && castRoute.DataTokens != null)
                {
                    symbolicName = castRoute.DataTokens["area"] as string;
                }
            }

            if (string.IsNullOrEmpty(symbolicName)) return helper.Content(url);
            
            var bundle = BundleRuntime.Instance.Framework.GetBundleBySymbolicName(symbolicName);
            if (bundle == null) return helper.Content(url);

            var bundleLocation = @"~\" + bundle.Location.Replace(HostingEnvironment.ApplicationPhysicalPath, String.Empty);
            url = url.Replace("~", bundleLocation);
            return helper.Content(url);
        }
    }
}